﻿const cloud = require("wx-server-sdk");
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const _ = db.command;

const deleteActivity = async (event) => {
  const wxContext = cloud.getWXContext();
  const openID = wxContext.OPENID;
  const { activityID } = event;
  if (!openID) {
    return { success: false, error: "未获取到用户信息" };
  }
  if (!activityID) {
    return { success: false, error: "缺少活动ID" };
  }
  try {
    // 1. 验证活动存在且当前用户为发布者
    const activity = await db.collection("Activity_Information")
      .doc(activityID)
      .get();
    if (!activity.data) {
      return { success: false, error: "未找到活动信息" };
    }
    if (activity.data.PublisherOpenID !== openID) {
      return { success: false, error: "仅发布者可删除活动" };
    }
    // 2. 事务删除所有关联数据
    await db.runTransaction(async (transaction) => {
      // 删除活动主信息
      await transaction.collection("Activity_Information")
        .doc(activityID)
        .remove();
      // 删除活动分组
      const groups = await transaction.collection("Activity_Group_Information")
        .where({ ActivityID: activityID })
        .field({ _id: true })
        .get();
      for (const group of groups.data) {
        await transaction.collection("Activity_Group_Information")
          .doc(group._id)
          .remove();
        // 删除用户报名记录（假设报名记录存在于Activity_Registration表）
      await transaction.collection("Group_Registration_Information")
      .where({ GroupID: group._id })
      .remove();
      }
      // 删除报名信息字段配置
      await transaction.collection("Activity_Registration_Information_Fields")
        .where({ ActivityID: activityID })
        .remove();
    }); return { success: true };
  } catch (error) {
    return {
      success: false,
      error: error.message || "删除活动失败"
    };
  }
};
exports.main = async (event, context) => {
  return deleteActivity(event);
};